package com.icss.helper;

import java.util.Map;

import com.icss.helper.StringHelper;

/**
 * @author shixiaolong
 * @dateApr 17, 2012
 */
public class StringHelper {

	/**
	 * �滻�����ַ�
	 * 
	 * @param sql
	 * @param params
	 */
	public String getSql(String sql, Object[] params) {
		StringHelper str = new StringHelper();
		int idx = -1;
		int i = 0;
		String tmp = sql;
		while ((idx = tmp.indexOf("?")) > -1 && i < params.length) {
			tmp = tmp.replaceFirst("\\?", "'"
					+ str.toSql(str.notEmpty(String.valueOf(params[i++]) )) + "'");
		}
		return tmp;

	}

	public static String notEmpty(Object value) {
		if (value == null) {
			value = "";
		}
		return String.valueOf(value).trim();
	}

	public static String toSql(String str) {
		String sql = new String(str);
		return Replace(sql, "'", "''");
	}
	
	/**
	 * @param source
	 * @param oldString
	 * @param newString
	 * @return
	 */
	public static String Replace(String source, String oldString, String newString) {
			StringBuffer output = new StringBuffer();

	        int lengthOfSource = source.length();   // Դ�ַ���
	        int lengthOfOld = oldString.length();   // ���滻�ַ���

	        int posStart = 0;   // ��ʼ����λ��
	        int pos;            // �������ַ��λ��?

	        while ((pos = source.indexOf(oldString, posStart)) >= 0) {
	            output.append(source.substring(posStart, pos));

	            output.append(newString);
	            posStart = pos + lengthOfOld;
	        }
	        if (posStart < lengthOfSource) {
	            output.append(source.substring(posStart));
	        }
	        return output.toString();
	    }
	
    public static String get(Map map,String keyName)
    {
    	return notEmpty(map.get(keyName));
    }
}
